<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午9:25
 */


use LaravelBook\Ardent\Ardent;

class ServiceBase extends Ardent {


    public function parseInput($model, $name, $default = null){
        $input = Input::get( $name, null);

        if(!is_null($input) && $input !== ''){
            $model->$name = $input;
        }else{
            $model->$name = $default;
        }
    }

    /**
     * 为表单中的checkbox准备数据
     * @param $entries model
     * @param string $display_field
     * @param array $selected menus[1]:0,menus[2]:1,menus[3]:0,menus[4]:1,menus[5]:1
     * @return array array(array('id'=>1,'display_name'=>'aaa'),array('id'=>1,'display_name'=>'aaa'),...)
     */
    public function prepareCheckboxDisplayForSearch($entries, $display_field = 'name', $selected = array()){
        $result = array();
        foreach($entries as $entry) {
            array_push($result, array('id'=> $entry['id'], 'display_name'=>$entry[$display_field], 'checked'=>(isset($selected[$entry['id']])) ? true : false));
        }
        return $result;
    }

    /**
     * 为表单中的select准备数据
     * @param $entries model
     * @param string $display_field
     * @param array $display_field
     * @return array array(array('id'=>1,'display_name'=>'aaa'),array('id'=>1,'display_name'=>'aaa'),...)
     */
    public static function prepareSelectGroupDisplayForSearch($entries, $display_field = 'name', $default_value = array()){
        $result = array();
        if(is_array($default_value)){
            $result = array_merge($default_value, $result);
        }
        foreach($entries as $entry) {
            $result[$entry['id']]= $entry[$display_field];
        }
        return $result;
    }

    public function prepareCheckboxForSearch($selected){
        $result = array();

        if(is_null($selected) || !empty($selected)) {
            return array();
        }

        foreach($selected as $key=>$value) {
            if($value == 1) array_push($result,  $key);
        }
        return $result;
    }

    public function getKeywordArrayById($entries, $selected_ids, $keyword = 'keyword'){
        $result = array();

        if(!is_array($entries) || !is_array($selected_ids)) {
            return array();
        }

        foreach($selected_ids as $key=>$value) {
            if($value == 1) array_push($result,  $entries[$key][$keyword]);
        }
        return $result;
    }


}

